webform.admin = liwe.module ( 'webform.admin', null, "Webform" );

webform.admin._dest_div = "system-content";
webform.admin._fields_options = [
				{ label : "text", value : "text" },
				{ label : "textarea" , value : "textarea" },
				{ label : "hidden" , value : "hidden" },
				{ label : "checkbox" , value : "checkbox" },
				{ label : "email" , value : "email" },
			   ];
webform.admin._list_forms = null;
webform.admin.admin_man = null;
// conterra' i risultati temporaneamente
webform.admin._tmp_res = null;
webform.admin.init = function ( dest_div )
{

	var _acts = [
		{ label : "Gestione Form" , func  : function () { webform.admin.form_manage (); } }, 
		{ func: function () { webform.admin.list_mails ('system-content'); } , label: 'Lista mails' }
		    ];

	var _plugin = [
		{
			label:   "Inserisci form",
			handler: webform.admin._jconed_handler, 
			context: webform.admin._jconed_context
		}
	];

	webform.admin.register ( _acts, _plugin );

	webform.admin._tmp_form_name = '';

	if ( ! webform.templates ) webform.load_templates ( function () { webform.admin.init_mod ( dest_div ) } );
	webform.admin.init_mod ( dest_div );	
};

webform.admin.init_mod = function ( dest_div )
{
	if ( ! dest_div ) dest_div = webform.admin.dest_div;
	webform.admin._admin_man_mail_init ( dest_div );
};

webform.admin.form_manage = function ()
{
	$( webform.admin._dest_div , webform.templates [ 'ADMIN_FORM_MANAGE_LAYOUT' ] );

	var post = { action : "webform.admin.main_list" }; 
	webform.ajax ( post, function ( data )
	{
		if ( data.main_list.length == 0 )
		{
			webform.admin.main_add ();
		}else{
			webform.admin.main_list_render ( data.main_list );
		};
	} );	

};
//{{{ MANAGE MAIN FUNCTION
webform.admin.main_list_render  = function ( data )
{
	var _html = new String.buffer();
	_html.add ( webform.templates [ 'ADMIN_FORM_MANAGE_LIST_START' ] );
	data.iterate ( function ( row )
	{
		_html.add ( String.formatDict ( webform.templates [ 'ADMIN_FORM_MANAGE_LIST_ROW' ] , row ) );
	} );
	_html.add ( webform.templates [ 'ADMIN_FORM_MANAGE_LIST_END' ]  );
	$ ( 'webform_list', _html.toString() );
};

webform.admin.main_add = function ( data )
{
	if ( typeof ( data ) == 'undefined' ) data = dict();
	to_dict ( data );
	webform.admin.main_form ( data );
	$("webform_edit_fields", "" );
	$("webform_fields", "" );
	$("webform_test", "" );
};

webform.admin.main_edit = function ( fname )
{
	var post = {  'action' : 'webform.admin.main_get', fname : fname }
	webform.ajax ( post , function ( data )
	{
		var data = data.main_get;
		webform.admin.main_form ( data );
		webform.admin.field_list ( fname );
		webform.admin.field_add ( fname );
	} );
	
};

webform.admin.main_form = function ( data )
{
	var f = new liwe.form5.instance ( "webform_main" );
	f.action = "webform.admin.main_set";
	var name = data.get ( 'name', '' ) ;
	var _dct = { 'label' : "Nome Univoco" , value : name  };
	if ( name != '' ) 
	{
		
		_dct [ 'disabled' ] = true;
		var _act = String.format ( "webform.admin.mail_set('%s')", name );
		f.add ( 'button' , 'mail', { 'value': "Mail" , 'onclick' : _act, 'class' : 'button red' } );
	}
	f.add ( "hidden", "sender", { 'value' : data.get ( 'sender') } );
	f.add ( "text", 'name', _dct );
	f.add ( "text", 'tpl_name', { 'label' : "Template personalizzato", value : data.get ( 'tpl_name' ) } );
	f.add ( "text", 'subject', { 'label' : "Oggetto", value : data.get ( 'subject' ) } );
	f.addEventListener ( "complete", function ( evt ) 
	{
		webform.admin._set_dest_mail();
		webform.admin.form_manage();
	} );

	f.addEventListener ( "render", function ()
	{
		webform.admin_render_dest_mail ();
		webform.admin_main_render_sender ();
	} );

	f.set ( "webform_edit", webform.templates [ 'ADMIN_MAIN_FORM' ] );
};


webform.admin.main_update_sender = function ( id_field, fname )
{
	webform.ajax ( { 'action' : "webform.admin.main_update", "sender" : id_field, "name" : fname  }, function ()
	{
		var f = liwe.form5.get ( "webform_main" );
		f.set_value ( 'sender' , id_field );
		webform.admin_main_render_sender();
	} );	
}; 

webform.admin_main_render_sender = function ()
{
	var f = liwe.form5.get ( "webform_main" );
	var id_sender = f.get_value ( 'sender');

	if ( ! id_sender || id_sender == 0 ) 
	{
		$ ( "webform-sender",  webform.templates [ "ADMIN_MAIN_SENDER_DEFAULT" ] );
		return;
	}

	webform.ajax ( { 'action' : 'webform.admin.get_field' , 'id_field' : id_sender }, function ( data )
	{
		to_dict ( data.get_field );
		var args = data.get_field.get ( "args_dict");
		args [ 'fname' ] = data.get_field.get ( "name" );
		$ ( "webform-sender", String.formatDict ( webform.templates [ "ADMIN_MAIN_SENDER" ], args ) );
	} );	


};



webform.admin_render_dest_mail = function ()
{
	var post = { 'action' : 'webform.ajax.list_destinations' } ;
	webform.ajax ( post , function ( res )
	{
		var destinations = list( res.destinations );
		var _html = liwe.utils.format_list ( destinations,
							webform.templates [ "ADMIN_MAIL_CHECK" ] ,
							webform.templates [ "ADMIN_MAIL_HEAD" ],
							webform.templates [ "ADMIN_MAIL_FOOT" ] ); 

		$( "webform-mail", _html );
		webform.admin._assign_dest_mail();
	} );
		
};

webform.admin._set_dest_mail = function ()
{
	var f = liwe.form5.get ( "webform_main" );
	var name = f.get_value ( "name" );
	if ( ! name ) return;


	var post = { 'action' : 'webform.admin.set_destination' , fname : name }; 

	var mail_ids = list();
	var chk_lst = document.querySelectorAll ( "#webform-mail input:checked" );
	for ( var i = 0 ; i < chk_lst.length; i++ )
	{
		mail_ids.push ( chk_lst [ i ].value );
	};	
	post [ 'mail_ids' ] =  mail_ids.join ( "|" );
	webform.ajax ( post );
};

webform.admin._assign_dest_mail = function ()
{
	/*ASSEGNA VALORI ALLE CHECK BOX*/
	var f = liwe.form5.get ( "webform_main" );
	var name = f.get_value ( "name" );
	if ( ! name ) return;
	var post = { 'action' : 'webform.ajax.list_form_destinations', fname : name };
	webform.ajax ( post, function ( assigned )
	{
		var assigned = list ( assigned.destinations );
		assigned.iterate ( function ( item )
		{
			var chk_lst = document.querySelectorAll ( "#webform-mail input" );
			for ( var i = 0; i < chk_lst.length; i++ )
			{
				var chk = chk_lst [ i ];
				if ( chk.value == item.value ) chk.checked = true; 
			};
		} );    
	} );    
};
//}}}
//{{{ MANAGES FIELD FORM
webform.admin.field_list = function ( fname )
{
	var post =  { action : "webform.ajax.get_form_fields", fname : fname };
	webform.ajax ( post , function ( data )
	{
		var ffields = list ( data.ffields );
		if ( ffields.length < 0 ) return;
		var _html =  new String.buffer();
		var _dct = { 'fname' : fname };
		_html.add ( String.formatDict (  webform.templates [ 'ADMIN_FORM_FIELD_LIST_START' ] , _dct ) );
		ffields.iterate ( function ( field )
		{
			to_dict ( field )
			if ( field.get ( 'id', 0 ) == 0 )return;
			to_dict ( field.args );
			var _dct = { 'fname' : field.name,
				     'name' :  field.args.get ( 'name', 'Non definito' ),
				     'label' : field.args.get ( 'label', 'Non definito'),
				     'field' : field.field,
				     'mandatory' : field.args.get ( 'mandatory' , 0 ),
				     'pos' : field.pos,
				     'id' : field.id
				   };
			_html.add ( String.formatDict (  webform.templates [ 'ADMIN_FORM_FIELD_LIST_ROW'] , _dct ) );

		} );
		_html.add ( webform.templates [ 'ADMIN_FORM_FIELD_LIST_END' ] );
		$( 'webform_fields', _html.toString() );
		webform.admin._render_dummy_form ( "webform_test", ffields )
	} );
	
}

webform.admin.field_edit = function ( id_field )
{
	var post = {  'action' : 'webform.admin.get_field', id_field : id_field }
	webform.ajax ( post , function ( data )
	{
		var data = dict ( data.get_field );
		console.log ( data ); 
		webform.admin.field_form ( data );
	} );
	
};

webform.admin.field_add = function  ( fname )
{
	var data = dict( { 'name' : fname } );
	webform.admin.field_form ( data );
	
}


webform.admin.field_move_pos = function ( fname, id_field, direction )
{
	var post = { action: 'webform.admin.move_field' , start_id : id_field, move : direction };
	webform.admin.ajax ( post, function ( data ) 
	{
		webform.admin.field_list ( fname );
	} );
};

webform.admin.field_form = function ( data )
{	
	if ( ! data.get ( 'name' , null ) )  return console.warn ( "Nome form non impostato" );
	var f = new liwe.form5.instance ( "webform_field" );
	f.action = "webform.admin.add_field";
	f.add ( 'hidden', 'name' , { value : data.get ( 'name', '' ) } );
	f.add ( 'hidden', 'pos' , { value : data.get ( 'pos', 0 ) } );
	f.add ( 'hidden', 'id_field', { value : data.get ( 'id', 0 ) } );
	f.add ( 'select' , 'field' , { 'label' : 'Tipo campo' , 'options' : webform.admin._fields_options , forced : true, value : data.get ( 'field', '' ) } );
	f.add ( 'textarea', 'args' , { 'label' : 'Parametri', value : data.get ( 'args' , '' ), mandatory : true }  );
	f.add ( 'checkbox', 'sender', { 'label' : 'Imposta come mail di spedizione', ignore : true, value : '1' } );

	f.addEventListener ( "submit", function ( evt )
	{
		var f = liwe.form5.get ( "webform_field" );
		if ( $( f.get_id ( "sender" ) ).checked ) webform.admin._bol_update_sender = true; 
	} );

	f.addEventListener ( "complete", function ( evt )
	{
		var data = evt.params.response.form_fields;
		webform.admin.field_add ( data.name );
		webform.admin.field_list ( data.name );
		

		if ( webform.admin._bol_update_sender )
		{
			webform.admin.main_update_sender  ( data.id, data.name);
			webform.admin._bol_update_sender = false;
		} 
	} ); 
	f.set ( "webform_edit_fields", webform.templates [ 'ADMIN_FIELD_FORM' ] );
	 
};
//}}}
// {{{ MANAGES MAIL TO SEND FORM INFO
webform.admin._admin_man_mail_init = function ( dest_div )
{
	if ( webform.admin.admin_mani_mail ) return;
	webform.admin.admin_man_mail = new AdminManager 
				( {
					'dest_res': dest_div,
					'list_action': "webform.admin.list_mails",
					'del_action':  "webform.admin.del_mail",
					'name' : "webform_mail",
					'mod_menu_actions': [
						{ func: "webform.admin.add_mail ('webform_mail:results')", 'class': 'mail_add', label: 'Nuovo indirizzo mail' }
								]
				} );

	webform.admin.admin_man_mail.set_row_fields (
				[
					[ "id_destination", "id_destination" ],
					[ "descr", "descr" ],
					[ "email", "email" ]
				]
				);

	webform.admin.admin_man_mail.cbacks [ 'row_manip' ] = webform.admin.mails_list_row_manip;
	webform.admin.admin_man_mail.cbacks [ 'edit_item' ] = function ( id ) { webform.admin.edit_mail ( id ); };
	webform.admin.admin_man_mail.cbacks [ 'del_item' ]  = function ( id ) { webform.admin.del_mail ( id ); };
	webform.admin.admin_man_mail.cbacks [ 'noresult' ]  = function ( id ) { webform.admin.add_mail (); };
							
};

/* webform.admin.list_mails ()
	param: dest_div ( string ) 	div di destinazione

	Mostra l'elenco delle mail disponibili 
*/
webform.admin.list_mails = function ( dest_div )
{
	webform.admin.admin_man_mail.show_list ( dest_div );
};

webform.admin.mails_list_row_manip = function ( ds, row )
{
	//console.debug ( "ROW-> argstxt: %s" , row [ 'argstxt' ] );
	row [ '_id' ]    = row [ 'id_destination' ]; 
	row [ '_email' ] = row [ 'email' ];
	row [ '_descr' ]  = row [ 'descr' ];
};

webform.admin.edit_mail = function ( id_mail )
{
	var vals = {
			'action' : 'webform.ajax.list_destinations',
			'id' : id_mail 
			};
	webform.admin.ajax ( vals , function ( data ){ 
								var eform = webform.admin._create_mail_form ( data [ 'destinations' ][ 0 ] , 
														     'webform.admin._edit_mail ()' );
								$( 'webform_mail:results', eform );
						     } );
};

webform.admin.add_mail = function ()
{
	var eform = webform.admin._create_mail_form ( '' ,  'webform.admin._edit_mail ()' );
        $( 'webform_mail:results', eform );
};

webform.admin._create_mail_form = function ( vals, cback ) 
{
	var f = new liwe.form.instance ( 'WF_edit_mail_form' );
	f.hidden ( { name : 'id_destination' , value : vals.get ( 'value' , '' ) } );
	f.email	( { label : 'email', name : 'email' , size: 40, validator: true, value : vals.get ( 'email' ,'' ) } );
	f.text	( { label : 'descrizione', name : 'descr' , size: 40,value : vals.get ( 'label', '' ) } );
	f.button ( { value: 'invia' , onclick: cback }); 
	return f.get ();
};


webform.admin._edit_mail = function ()
{
	var f = liwe.form.get ( 'WF_edit_mail_form' );
	var vals = f.get_values ();
	vals [ 'action' ] = 'webform.admin.edit_mail';
	webform.ajax ( vals , function ( data ) { webform.admin.list_mails () } ); 
};


webform.admin.del_mail = function ( ids ) 
{
	webform.ajax ( { action: 'webform.admin.del_mail', 'ids': ids } , function ( data ) { webform.admin.list_mails () } );
};
//}}}
webform.admin._render_dummy_form = function ( dest_div, form_fields )
{
	if ( ! dest_div ) dest_div = "WF-dummy-form";
	var f = new liwe.form5.instance ( 'WF_dummy_form' );
	to_list ( form_fields );
	var tpl = new String.buffer();
	tpl.add ( webform.templates [ 'ADMIN_FORM_START' ] );

	var f  = new liwe.form5.instance ( "WF_dummy_form" );
	form_fields.iterate ( function ( obj )
	{
		
		var args = to_dict ( obj.args )
		if ( obj.field == 'hidden' )
		{
			obj [ 'field' ] = 'text';
			tpl.add ( String.formatDict ( webform.templates [ 'ADMIN_FORM_FIELD_HIDDEN' ] , args ) );
			
		} else {
			args [ '_label' ] = "%(" + args [ 'name' ] + "-label)s";
			args [ '_name' ] = "%(" + args [ 'name' ] + ")s";
			tpl.add ( String.formatDict ( webform.templates [ 'ADMIN_FORM_FIELD' ] , args ) );
			f.add ( obj.field, args.name ,  args );
		};
			
	} );
		
	tpl.add ( webform.templates [ 'ADMIN_FORM_END' ] );
	f.set ( dest_div, tpl.toString() );
		
};
//{{{ JCONED WEB FORM
webform.admin._jconed_form = function ( values )
{
	values = values || {};
	console.debug ( "VALUES: %o", values );

	webform.ajax ( { action: "webform.ajax.list_forms" }, function ( res )
	{
		var forms = res [ 'forms_list' ];

		var f = new liwe.form.instance ( "jconed-webform" );
		var opts = [];

		forms.iterate ( function ( frm )
		{
			opts.push ( { label: frm.name, value: frm.name } );
		} );

		f.hidden ( '_module', 'webform' );
		f.hidden ( '_title', 'WebForm' );

		f.select ( { label: "Form", name: "name", options: opts, force_select: true, mandatory: true, value: values.get ( 'name' ) } );
		f.button ( { value: "Conferma", onclick: "jconed.render_plugin('jconed-webform')" } );

		jconed.toolbar.set_context ( f.get () );
	} );
};

webform.admin._jconed_handler = function ( editor )
{
	webform.admin._jconed_form ();
};

webform.admin._jconed_context = function ( editor )
{
	var item = jconed.get_plugin_selection ();
	if ( ! item ) return;
	if ( ! liwe.dom.has_class ( item, 'liwe-plugin-webform' ) ) return;

	pre = item.getElementsByTagName ( "pre" );
	if ( ! pre.length ) return;

	pre = pre [ 0 ];

	eval ( 'var values = ' + pre.innerHTML );

	webform.admin._jconed_form ( values [ 'params' ] );
};
//}}}

/* webform.admin._clean_rel_table ();
	param: fname ( string )		nome della form
	param: optimize ( string ) 	se passato, la funzione ottimizza le tabelle

	Ottimizza le tabelle relazionali usate per salvare le mail di destinazione delle webform.
	Se passato il parametro 'optimize' la funzione si ooccuperà di eliminare tutti gli orfani nella tabella webform_rel 
*/
webform.admin._clean_rel_table = function ( fname, optimize )
{
	webform.admin.ajax ( { action: "webform.admin.clean_rel_table", fname : fname, optimize : optimize } );	
};

webform.admin.optimize_rel_table = function ()
{
	webform.admin.ajax ( { action: "webform.admin.clean_rel_table", optimize : "yes" } );	
};
//{{{ OLD CODE
/*
webform.admin._admin_manager_init = function ( dest_div )
{
	if ( webform.admin.admin_man ) return;
	webform.admin.admin_man = new AdminManager 
				( {
					'dest_res': dest_div,
					'list_action': "webform.admin.list",
					'del_action':  "webform.admin.del_fields",
					'name':  "webform_fields",
					'mod_menu_actions': [
						{ func: "webform.admin.set_dest_form ('webform_fields:results')", 'class': 'mail_select', label: 'Destinazione form' },
						{ sep: 1 },
						{ func: "webform.admin.add_field_form ('webform_fields:results')", 'class': 'new_field', label: 'Nuovo campo form' },
						{ sep: 1 },
						{ func: "webform.admin.add_form ()",  'class': 'new_form', label: 'Nuova Form' },
						{ sep: 1 },
						{ func: "webform.admin.list ('system-content')", 'class': 'lista_categorie', label: 'Lista Forms' }
								],
					'filter_form' : webform.admin._filter_form,
					'filter_form_name' : "WF_admin_filter_form"
				} );

	webform.admin.admin_man.set_row_fields (
				[
					[ "name", "_name" ],
					[ "tipo", "field" ],
					[ "params", "_args" ],
					[ "move", "_move" ]
				]
				);


	// webform.admin.admin_man.templates ['table_start' ] = webform.admin.templates [ 'table_start' ];
	// webform.admin.admin_man.templates [ 'table_row' ] = webform.admin.templates [ 'table_row' ];

	webform.admin.admin_man.cbacks [ 'row_manip' ] = webform.admin.list_row_manip;
	webform.admin.admin_man.cbacks [ 'edit_item' ] = function ( id ) { webform.admin.edit_field_form ( 'WF-dummy-form' , '' , id ); };
	webform.admin.admin_man.cbacks [ 'del_item' ]  = function ( id ) { webform.admin.del_field_form ( dest_div, id ); };
							
};

webform.admin.list_row_manip = function ( ds, row )
{
	//console.debug ( "ROW-> argstxt: %s" , row [ 'argstxt' ] );
	row [ '_id' ]    = row [ 'id' ]; 
	row [ '_fname' ] = row [ 'name' ];
	row [ '_name' ]  = row [ 'args' ][ 'name' ];
	row [ '_args' ]  = webform.admin._fmt_params ( row [ 'argstxt' ] , '' );
	row [ '_move' ]  = String.formatDict ( webform.templates [ 'WF-move-field' ], { id : row [ 'id' ], fname : row [ 'name' ] } );
};
*/

/* webform.admin._filter_form ()
	param: dest_div ( string ) 	div di destinazione

	crea il form per la scelta del form da editare ed il div dove verra' visuallizzata la preview

webform.admin._filter_form = function ( dest_div )
{
	webform.ajax ( { action : "webform.ajax.list_forms" } , function ( data )
				{
					if ( data [ 'forms_list' ].length < 1 ) return;

					var opts = [ { label : "Seleziona", value : "" } ];
					data [ 'forms_list' ].iterate ( function ( v )
									{
										opts.push ( { label : v.name , value : v.name } );
									} );
					webform.admin._list_forms = opts;
					var f = new liwe.form.instance ( 'WF_admin_filter_form' );
					f.select ( { label : "Seleziona form", options : opts, name : "fname", 
						     onchange : "webform.admin._filter_apply( this.value )" } );
					f.workspace ( { name: "WF-dummy-form" } );
					f.workspace ( { name: "WF-dest-mails" } );
					f.set ( dest_div );
				} ) ;
	
};

*/
/* webform.admin._filter_apply ()
	param: name ( string ) 		nome del form selezionato

	Applica il filtro alla ricerca e visualizza i risultati
webform.admin._filter_apply = function ( name )
{
	// clear temp results
	webform.admin._tmp_res = null;
	webform.admin.admin_man.search_start ();
	webform.admin.edit_field_form ( "WF-dummy-form", name, '' );
	webform.admin.get_related_mails ( "WF-dest-mails" , name );
};
*/

/* webform.admin.add_form ()
	param: dest_div ( string )      div di destinazione
	param: form_name ( string )	nome del form 

	Chiama la funzione per il form di inserimento del nome del form
	o di inserimento campo 
webform.admin.add_form = function ( dest_div , form_name )
{
	if ( $( 'WF-dummy-form' ) ) 
	{
		$( 'WF-dummy-form', '' );
		$( "WF-dest-mails" , '' );
	}
	$( dest_div, webform.templates [ 'WF-admin-layout' ] ); 
	if ( !form_name ) 
	{
		webform.admin._set_form_name ( 'WF-admin-options' );
	} else {
		// aggiorna la lista di form disponibili e seleziona l'ultima inserita
		if ( $( 'WF_admin_filter_form' ) )
		{
			webform.admin._list_forms.push ( { "label" : form_name, "value" : form_name } );
			var f = liwe.form.get ( 'WF_admin_filter_form' );
			f.select_set_values ( 'fname' , webform.admin._list_forms );
			$( "WF_admin_filter_form@fname" ).options.iterate ( function ( v, k ) 
								{
									if ( v.text == form_name ) $( "WF_admin_filter_form@fname" ).selectedIndex = k;
								});
		}
		webform.admin.add_field_form ( 'WF-admin-options', form_name );
	}
};

*/
/* webform.admin._set_form_name ()
	param: dest_div ( string )      div di destinazione

	Crea il form per inserire il nome del nuovo form
webform.admin._set_form_name = function ( dest_div )
{
	get_field_name = function ( dest_div, nfield )
				{
					var f = liwe.form.get ( 'set_form_name' );
					fvalue = f.get_value ( nfield );
					webform.admin._check_form_name ( dest_div, fvalue );
				};
	var f = new liwe.form.instance ( "set_form_name" );
	f.text ( { label: "Nome del form", name : "name", mandatory : true, maxlength : "50" } );
	f.button ( { label: "Prosegui", value : "Prosegui", onclick : "get_field_name ( '" + dest_div + "', 'name' )" } );
	f.set ( dest_div );
};

*/
/* webform.admin._check_form_name ()
	param: dest_div ( string )      div di destinazione
	param: name ( string )		nome del form da creare

	Controlla che non esista un form con il nome scelto
webform.admin._check_form_name = function ( dest_div, name )
{
	var vals = {
			"name" : name,
			"action" : "webform.admin.check_form_name" 	
		   };
	webform.admin.ajax ( vals , function ( data ) {
								if ( data [ 'name' ] )
								{
									alert ( "Nome del form esistente ( " + data [ 'name' ] + " )"  );
									webform.admin._set_form_name ( dest_div );
								}else {
									webform.admin.add_form ( dest_div, name );
								}
							} );
};
*/

/* webform.admin.list ()
	param: dest_div ( string ) 	div di destinazione

	Mostra i risultati dopo la selezione del form
webform.admin.list = function ( dest_div )
{
	webform.admin._tmp_res = null;
	webform.admin.admin_man.show_list ( dest_div );
};
*/


/* webform.admin._render ()
	param: dest_div ( string ) 	div di destinazione
	
	inserisce il template per il form di inserimento campi e la preview del form
webform.admin.render = function ( dest_div )
{
	$( dest_div, webform.templates [ 'WF-admin-layout' ] );
	webform.admin.add_field_form ();
};

*/
/* webform.admin._render_dummy_form ()
	param: dest_div ( string ) 	div di destinazione
	param: form_fields ( object ) 	oggetto contenente un lista dei campi del form

	Mostra la preview del form 
webform.admin._render_dummy_form = function ( dest_div, form_fields )
{
	
	if ( ! dest_div ) dest_div = "WF-dummy-form";
	var f = new liwe.form.instance ( 'WF_dummy_form' );
	form_fields.iterate ( function ( obj ) 
	{
		if ( obj.field == 'hidden' )
			{
				flabel = obj.args.get ( 'label' , '' );
				fval = obj.args.get ( 'value' , '' );
				f.label ( { label: '( hidden ) ' + flabel , value: fval } );
			}
		f [ obj.field ] ( obj.args );
				
	} );

	f.set ( dest_div );
	if ( ! webform.admin._tmp_res ) webform.admin._tmp_res = form_fields;
};
*/



/* webform.admin.edit_field_form ()
	param: dest_div ( string ) 	div di destinazione
	param: name ( string ) 		nome del form
	param: id ( int ) 		id del campo selezionato

	controlla se i campi del form selezioanto siano già disponibili, altrimenti
	fa la chiamata ajax per ottenerli. Quindi chiama _edit_field_form ()
webform.admin.edit_field_form = function ( dest_div, name, id )
{
	if ( webform.admin._tmp_res )
	{
		webform.admin._edit_field_form ( dest_div, name, id );
		return ;	
	}
	webform.ajax ( { action : "webform.ajax.get_form_fields", fname : name, id : id } , function ( data ) 
					{
						if ( data [ 'ffields' ].length < 1 ) return;
						webform.admin._tmp_res = data [ 'ffields' ];
						webform.admin._edit_field_form ( dest_div, name, id );
					} );
};
*/	
/* webform.admin._edit_field_form ()
	param: dest_div ( string ) 	div di destinazione
	param: name ( string ) 		nome del form
	param: id ( int ) 		id del campo selezionato
webform.admin._edit_field_form = function ( dest_div, name, id )
{
	if ( id ) 
	{
		liwe.lightbox.easy ( 'WF-admin-lb', 'Edit form field', 600, 250 );
		$( 'WF-admin-lb' , webform.templates [ 'WF-admin-layout' ] );
		webform.admin._edit_field ( 'WF-admin-options' , webform.admin._tmp_res, id );
	}
	webform.admin._render_dummy_form ( dest_div , webform.admin._tmp_res );
};
*/	

/* webform.admin._edit_field ()
   param: dest_div		div di destinazione
   param: fields 		oggetto con i valori dei campi
   param: id			id del campo da modificare

   crea il form per editare un campo 
webform.admin._edit_field = function ( dest_div, fields, id )
{
	if ( ! dest_div ) dest_div = "WF-dummy-form";
	fields.iterate ( function ( v )
				{
					if ( v.get ( 'id', '' ) == id ) field = v; 
				} );
	var ef = new liwe.form.instance ( 'WF_fields_form' );
	var fmt_args = webform.admin._fmt_params ( field.argstxt, '' );
	var opts = webform.admin._fields_options;

	ef.hidden ( { name : "id", value : field.id } );
	ef.hidden ( { name : "name", value : field.name } );
	ef.hidden ( { name : "pos", value : field.pos } );
	ef.select ( { label: "Tipo campo", name: "field" , options : opts, mandatory : true, nonl: false } );
	ef.textarea ( { label: "Parametri", name: "args", maxlength : "500", cols: "50", value: fmt_args , mandatory: true, nonl: false } );
	ef.button ( { label: "Modifica campo", name: "add_field", value: ">>", onclick: "webform.admin._add_field ( 'WF-dummy-form' );" } );
	ef.set ( dest_div );
	$( "WF_fields_form@field" ).options.iterate ( function ( v, k ) 
							{
								if ( v.text == field.field ) $( "WF_fields_form@field" ).selectedIndex = k;
							});
};

webform.admin.move_field = function ( id, fname, move )
{
	webform.admin.ajax ( { action: 'webform.admin.move_field' , start_id : id, move: move } , function ( data ) 
											{
												webform.admin._filter_apply  ( fname );
											} );
};
*/
/* webform.admin.add_field_form ()
   param: dest_div		div di destinazione
   param: name			nome del form

   form che servirà a creare la webform
webform.admin.add_field_form = function ( dest_div, name )
{
	if ( ! dest_div ) dest_div = "WF-admin-options";
	if ( ! name ) 
	{
		name = $v( 'WF_admin_filter_form@fname' ) ;
		if ( ! name ) 
		{
			alert ( "Nessuna form selezionata" );
			return;
		}
			
	}

	var f = new liwe.form.instance ( "WF_fields_form" );
	var opts = webform.admin._fields_options; 
	f.hidden ( { name: "name", value: name } ); // form name
	f.select ( { label: "Tipo campo", name: "field" , options : opts, mandatory : true, nonl: false } );
	f.textarea ( { label: "Parametri", name: "args", maxlength : "200" , cols: "50", mandatory: true, nonl: false } );
	f.button ( { label: "Aggiungi campo", name: "add_field", value: ">>", onclick: "webform.admin._add_field ();" } );
	f.set ( dest_div );
};
*/

/* webform.admin._add_field ();
	param: dest_div ( string ) 	div di destinazione

	chiamata ajax per il salvataggio/modifica di un campo del form
webform.admin._add_field = function ( dest_div )
{
	//clear temp results
	webform.admin._tmp_res = null;
	//il div di destinazione della dummy form puo' cambiare. Non indicandone nessuno
	//verra' utilizzato il div del layout di webform a meno che non esista quello creato 
	//all'interno di admin_manager
	if ( ! dest_div ) 
	{
		dest_div = 'WF-admin-form';
		var list_dest_div = 'WF-admin-options';
		if ( $( 'WF-dummy-form' ) ) dest_div = 'WF-dummy-form';
	}
	var f = liwe.form.get ( 'WF_fields_form' );
	var vals = f.get_values ();
	vals [ 'action' ] = "webform.admin.add_field";

	vals [ 'args' ] = webform.admin._fmt_params ( vals [ 'args' ], true );

	if ( f.check () )
	{
		console.debug ( "VALS : %o" , vals );
		webform.admin.ajax ( vals , function ( data )
						{
							//console.debug ( "ADD FIELD: %o" , data );
							if ( ! data [ 'form_fields' ] ) return;
							webform.admin._render_dummy_form ( dest_div, data [ 'form_fields' ] );
							webform.admin._filter_apply ( data [ 'form_fields' ][0][ 'name' ] );
							liwe.lightbox.close ();
						} );
	}
};
*/
/* webform.admin.del_field_form ();
	param: dest_div ( string )	div di destinazione
	param: id ( int ) 		id del campo da eliminare
					
	chiamata ajax per eliminare un campo  tramite id
	NOTE: webform.admin.del_fields supporta anche id multipli separati da pipe, 
	ma non questa funzione 
webform.admin.del_field_form = function ( dest_div, id )
{
	var field;
	var msg = new String.buffer ();
	var lastfield = ( webform.admin._tmp_res.length < 2 ) ? true : false;
	webform.admin._tmp_res.iterate ( function ( v, k )
						{
							if ( v [ 'id' ] == id ) field = v; 
						} );
	msg.add ( "Sicuro di voler eliminare il campo '" + field.args.name + "' ? "  );
	if ( lastfield ) msg.add ( "\n( Il form ha solo questo campo e quindi verra' eliminato completamente )" );	
	var conf = confirm ( msg );
	if ( conf )
	{
		webform.admin.ajax ( { action : "webform.admin.del_fields", ids : id }, function ( data )
							{
								if ( lastfield )
								{
									webform.admin._clean_rel_table ( field.name, 'yes' );
								}
								webform.admin._filter_apply ( field.name );
							} );
	}
	
};
*/
/* webform.admin.set_dest_form ();
	param: dest_div ( string )	div di destinazione
	
	Prepara la lista delle mail di destinazione disponibili e quella delle mail selezionate,
	quindi chiama _set_dest_form che creera' il form passandogli i valori ottenuti
webform.admin.set_dest_form = function ( dest_div )
{
	function selected_ids ( fname, opts, msg )
	{
		 webform.admin.ajax ( { action: "webform.ajax.list_form_destinations", fname : fname } , function ( seldata )
                                        {
                                                var sel = ( ! seldata [ 'destinations' ] ) ? [] : seldata [ 'destinations' ];
                                                webform.admin._set_dest_form ( dest_div, opts, sel , msg );
                                        } );

	}
	webform.admin.ajax ( { action: "webform.ajax.list_destinations" } , function ( data )
					{
						var opts = ( ! data [ 'destinations' ] ) ? [] : data [ 'destinations' ];
						var msg = ( ! data [ 'destinations' ] ) ? 'Nessuna mail trovata' : '';
						selected_ids ( webform.admin._tmp_res [ 0 ][ 'name' ] , opts, msg );
					} );
};
*/

/* webform.admin._set_dest_form ();
	param: dest_div ( string )      div di destinazione
	param: opts ( object ) 		lista delle mail disponibili
	param: sel ( object ) 		lista delle mail selzionate
	param: msg ( string ) 		messaggio per l'utente

	Crea il form con l'elenco delle mail disponibili/selezionate
webform.admin._set_dest_form = function ( dest_div, opts , sel , msg )
{
	if ( opts.length < 1 ) 
	{
		$( dest_div, msg );
		return; 
	}

	var selecteds = {};

	sel.iterate ( function ( v, k ) { selecteds [ v.value ] = 1; } );

	var f = new liwe.form.instance ( 'WB-dests-form' );
	f.hidden ( { name: "fname", value: webform.admin._tmp_res  [ 0 ][ 'name' ] } );
	opts.iterate ( function ( v , k ) 
			{
				selbox = false;

				if ( selecteds.get ( v.value ) ) selbox = true;
				f.checkbox ( { label : v.label, name : "cb_" + v.value, value : v.value, checked : selbox } );
			} );
	f.button ( { value : "Assegna", name : "butt-dests", onclick : "webform.admin.set_destination ( '" + dest_div + "' )" } );
	$( dest_div , f.get () );
	
};
*/

/* webform.admin.set_destination ();
	param: dest_div ( string )      div di destinazione

	Passa gli id delle mail selezionate alla chiamata ajax che le salverà su database.
webform.admin.set_destination = function ( dest_div )
{
	if ( ! dest_div ) dest_div = 'WF-dest-mails';
	var f = liwe.form.get ( 'WB-dests-form' );
	var vals = f.get_values();
	var ids_array = [];
	vals.iterate ( function ( v, k )
			{
				if (  k.substr ( 0, 3 ) == 'cb_' && v ) ids_array.push ( v );
			} );
	vals [ 'mail_ids' ] = ids_array.join ( '|' );
	vals [ 'action' ] = "webform.admin.set_destination";
	
	webform.admin.ajax ( vals, function ( data ) {
							if ( ! data [ 'destinations' ].length ) 
							{
								alert ( 'Non ci sono mail assegnate a questo form !' );
								var res = [];
								webform.admin.get_related_mails ( '', '', res );
								return;
							}
							webform.admin.get_related_mails ( '', '', data [ 'destinations' ] );
						     } );
};
*/

/* webform.admin.get_related_mails ();
	param: dest_div ( string )      div di destinazione
	param: fname ( string ) 	nome del form
	param: res ( object ) 		lista delle mail legate al form 
	param: cback ( function ) 	funzione di callback

	Ottiene la lista delle mail relative al form identificato da fname e ne formatta l'output.
	Passando il parametro res la funzione non fa la chiamata ajax.
	Passando il parametro cback, la funzione di callback verrà chiamata al posto della formattazione 
	dell' output

webform.admin.get_related_mails = function ( dest_div, fname, res, cback )
{

	if ( ! dest_div ) dest_div = 'WF-dest-mails';

	function frmt_output ( res, dest_div )
	{
		out = new String.buffer ();
		res.iterate ( function ( v ) 
				{
					out.add ( String.formatDict ( webform.templates [ 'WF-admin-list-mails-row' ] , v ) );  
				} );
		var dct = { list_mails : out };
		$( dest_div , String.formatDict ( webform.templates ['WF-admin-dest-mails'], dct ) ); 
	};

	if ( res )
	{
		frmt_output ( res , dest_div );
		return;
	}

	var vals = {};	
	vals [ 'fname' ] = fname;
	vals [ 'action' ] = "webform.ajax.list_form_destinations";
	webform.admin.ajax ( vals, function ( data ) {
							if ( cback ) 
							{
								cback ();
								return;
							}

							frmt_output ( data [ 'destinations' ], dest_div );
						     } );
}; 
*/

/* webform.admin.move_pos ()
	param: dir ( string ) 	possibili valori: up/down/del
	param: id ( int ) 	id del campo da spostare
	
 NOTE: non utilizzata ( per usare il metodo replace di form.js )
webform.admin._replace_form = function ( inst , form_div )
{
	var f = new liwe.form.instance ( inst );
	f.replace ( form_div );
};
/*

/* webform.admin._fmt_params ();
	param: txt ( string ) 	stringa contenente gli argomenti del campo
	param: db  ( boolean ) 	se TRUE formatta la stringa txt per essere salvata du db
				se FALSE la formatta per il form di inserimento/modifica
webform.admin._fmt_params = function ( txt, db )
{
	if ( typeof txt != "string" ) return '';
	// se db è true formatta il testo che per essere salvato nel db
	if ( db || db != '' ) 
	{
		txt = txt.trim ().replace ( /[\n\r]/g, "," ).replace ( /,,* /g, "," );
		if ( txt.substr ( -1 ) == ',' ) txt = txt.substr ( 0, txt.length -1 ); 
		if ( txt.charAt ( 0 ) != '{' ) txt = "{" + txt + "}";
		return txt;
	}
	// formatta il testo che proviene dal db
	txt = txt.trim ().replace ( /,/g , "\n" ).replace ( /({)|(})/g, "");
	return txt;
};
*/
/* webform.admin._fill_tmp_res ()
	param: none
	popola la variabile interna _tmp_res con i campi del form selezionato.
webform.admin._fill_tmp_res = function ()
{
	if ( ! $v( 'WF_admin_filter_form@fname' ) ) return;
	name = $v( 'WF_admin_filter_form@fname' );
	webform.admin.ajax ( { action: "webform.ajax.get_form_fields", fname : name } , function ( data )
					{
						webform.admin._tmp_res = data [ 'ffields' ];
					} );
	// webform.get_related_mails ( name, function () { webform.admin._tmp_res = data [ 'destiantions' ]; } );
};
*/ 
//}}}
